﻿using System;
using System.IO;
using System.Text;

namespace Pvf.Core.Contents
{
    public sealed class PvfObjectContent<TObj> : PvfContent<TObj>
    {
        private TObj _obj;
        public override TObj Data => _obj;

        public override bool Load(Encoding encoding, IPvfModule module)
        {
            if (_obj != null)
            {
                return true;
            }

            if (!base.Load(encoding, module))
            {
                return false;
            }

            if (BytesData.Length < 2)
            {
                return true;
            }

            var converter = PvfObjectBuilder.Build(typeof(TObj), Index.Env);

            if (converter == null)
            {
                return false;
            }

            using (var ms = new MemoryStream(BytesData))
            {
                var s1 = ms.ReadByte();
                var s2 = ms.ReadByte();
                if (s1 != 0xb0 || s2 != 0xd0)
                {
                    throw new NotSupportedException($"不支持的数据格式({Index.FileName})");
                }

                if (converter is ITextPvfConverter<TObj> streamPvfConverter)
                {
                    using (var reader = new StreamReader(ms, encoding))
                    {
                        _obj = streamPvfConverter.Deserialize(reader, module);
                    }
                }
                else if (converter is IBinaryPvfConverter<TObj> binaryPvfConverter)
                {
                    using (var reader = new BinaryReader(ms))
                    {
                        _obj = binaryPvfConverter.Deserialize(reader, module);
                    }
                }
                else
                {
                    throw new NotSupportedException("不支持的转换器");
                }
            }

            return true;
        }
    }
}
